import axios from 'axios';

const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000';

const api = axios.create({
  baseURL: `${API_BASE_URL}/api`,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now(),
      };
    }
    
    // 添加认证token
    const token = localStorage.getItem('accessToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    const originalRequest = error.config;

    // 处理网络错误
    if (!error.response) {
      console.error('网络错误:', error.message);
      return Promise.reject({
        response: {
          data: {
            error: '网络连接失败，请检查网络设置',
          },
        },
      });
    }

    // 处理401错误 - token过期
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;

      try {
        const refreshToken = localStorage.getItem('refreshToken');
        if (refreshToken) {
          const response = await axios.post(`${API_BASE_URL}/api/auth/refresh`, {}, {
            headers: {
              Authorization: `Bearer ${refreshToken}`,
            },
          });

          const { access_token } = response.data;
          localStorage.setItem('accessToken', access_token);
          
          // 重试原请求
          originalRequest.headers.Authorization = `Bearer ${access_token}`;
          return api(originalRequest);
        }
      } catch (refreshError) {
        // 刷新失败，清除token并跳转到登录页
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        window.location.href = '/login';
        return Promise.reject(refreshError);
      }
    }

    // 处理服务器错误
    const { status, data } = error.response;
    
    switch (status) {
      case 400:
        console.error('请求错误:', data.error);
        break;
      case 401:
        console.error('未授权访问:', data.error);
        break;
      case 403:
        console.error('禁止访问:', data.error);
        break;
      case 404:
        console.error('资源不存在:', data.error);
        break;
      case 422:
        console.error('数据验证错误:', data.error);
        break;
      case 500:
        console.error('服务器错误:', data.error);
        break;
      default:
        console.error('未知错误:', data.error);
    }

    return Promise.reject(error);
  }
);

export default api;
